package com.nulldev.util.web.HttpServer3.extensions.nCaptcha.backend;

import com.nulldev.util.languages.json.uniapi.UniJsonValue;
import com.nulldev.util.web.HttpServer3.Response;
import com.nulldev.util.web.HttpServer3.extensions.nCaptcha.backend.user.User;
import com.nulldev.util.web.HttpServer3.extensions.nCaptcha.backend.util.UUIDCookieLoader;
import com.nulldev.util.web.HttpServer3.legacyPages.v1.RequestType;
import com.nulldev.util.web.HttpServer3.pages.v3.HttpPage3;

public class ValidUID extends HttpPage3 {

	public ValidUID() {
		super("/captcha/check_uid", true);
		super.setCachingMethod(CachingMethod.NO_CACHE);
	}

	@Override
	public Response onRequest(final Request request) {
		if (!request.getType().equals(RequestType.POST)) {
			return new Response(405);
		}

		if (!request.hasInputStream()) {
			return new Response(411);
		}

		if (!UUIDCookieLoader.hasCookie(request)) {
			return new Response(400);
		}

		final User user = UUIDCookieLoader.userFromRequest(request);
		if (user == null) {
			return new Response(403);
		}

		final String body = toString(request.getInputStream());

		if (!body.startsWith("{") && !body.endsWith("}")) {
			return new Response(400);
		}

		final UniJsonValue object = UniJsonValue.parse(body);
		final UniJsonValue response = UniJsonValue.object(3);
		final String uid = object.getString("uid", null);

		if (uid == null || uid.isEmpty()) {
			response.add("uid", uid);
			response.add("valid", false);
			return new Response(200, response, response);
		} else if (user.getExpectedResults() != null && user.getExpectedResults().length > 0 && user.uuid().equals(uid)) {
			response.add("uid", uid);
			response.add("valid", true);
			response.add("expiry", user.time());
			return new Response(200, response, response);
		} else {
			response.add("uid", uid);
			response.add("valid", false);
			return new Response(200, response, response);
		}
	}
}
